package com.talent.web.config.security;

import com.google.gson.Gson;
import com.talent.web.enums.ResponseEnum;
import com.talent.web.model.TalentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @ClassName：TalentAccessDeniedHandler
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: 无权限拒绝访问
 */
@Component
public class TalentAccessDeniedHandler implements AccessDeniedHandler {

    private static final Logger logger = LoggerFactory.getLogger(TalentAccessDeniedHandler.class);

    @Autowired
    private Gson gson;
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException {
        logger.error(ex.getMessage());
        //无权限访问该资源，请联系管理员
        TalentResult<String> result = TalentResult.error(ResponseEnum.FORBIDDEN);
        logger.error("权限不足");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        String json = gson.toJson(result);
        writer.println(json);
    }
}
